<template>
  <div class="users-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input @clear="getUserList" clearable v-model="query" placeholder="请输入内容" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="16"><el-button type="primary" @click="addDialogVisible = true">添加用户</el-button></el-col>
      </el-row>

      <el-table
        border
        :data="userList"
        stripe
        style="width: 100%">
        <el-table-column
          type="index"
          width="50">
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色">
        </el-table-column>
        <el-table-column
          prop="mg_state"
          label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="changeUser(scope.row.id)"/>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="delUser(scope.row.id)"/>
            <el-tooltip :enterable="false" class="item" effect="dark" content="分配角色" placement="top">
              <el-button size="mini" type="warning" icon="el-icon-setting" @click="distributeRoles(scope.row)"/>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="3"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <el-dialog
      @close="closeAddDialog"
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%">
      <el-form :model="addRuleForm" :rules="addRules" ref="addRuleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addRuleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addRuleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      @close="closeEditDialog"
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%">
      <el-form :model="editRuleForm" :rules="editRules" ref="editRuleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名称">
          <el-input v-model="editRuleForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetEditForm">取 消</el-button>
        <el-button type="primary" @click="editUser(editRuleForm.id)">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      @close="closeRolesDialog"
      title="分配角色"
      :visible.sync="rolesDialogVisible"
      width="50%">
      <el-form ref="rolesRuleFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="当前用户 : ">
          <span>{{rolesRuleForm.username}}</span>
        </el-form-item>
        <el-form-item label="当前角色 : ">
          <span>{{rolesRuleForm.role_name}}</span>
        </el-form-item>
        <el-form-item label="分配角色 : " >
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in newRolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var validateEmail = (rule, value, callback) => {
      const emailReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if(emailReg.test(value)) {
        callback()
      }
      callback(new Error('请输入正确格式的邮箱'))
    }
    var validateMobile = (rule, value, callback) => {
      const mobileReg = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if(mobileReg.test(value)) {
        callback()
      }
      callback(new Error('请输入正确格式的手机号'))
    }
    return {
      userList: [],
      query: '',
      pagenum: 1,
      pagesize: 3,
      currentPage: 1,
      total: 0,
      addDialogVisible: false,
      addRuleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editRuleForm: {},
      editRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ]
      },
      rolesRuleForm: {},
      rolesDialogVisible: false,
      newRolesList: [],
      selectRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: {
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      })

      if(res.meta.status != 200) {
        this.$message.error(res.meta.msg)
        return false
      }

      this.userList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.pagenum = val
      this.getUserList()
    },
    async changeState(info) {
      const { data: res } = await this.$http.put(`users/${info.id}/state/${info.mg_state}`)

      if(res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        return false
      }

      this.$message.success(res.meta.msg)
    },
    closeAddDialog() {
      this.$refs.addRuleForm.resetFields()
    },
    addUser() {
      this.$refs.addRuleForm.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('users', {
            username: this.addRuleForm.username,
            password: this.addRuleForm.password,
            email: this.addRuleForm.email,
            mobile: this.addRuleForm.mobile
          })
          if(res.meta.status !== 201) {
            this.$message.error(res.meta.msg)
            return false
          }

          this.$message.success(res.meta.msg)
          this.getUserList()
          this.addDialogVisible = false

        } else {
          this.$message.error('表单提交信息有误！')
          return false
        }
      })
    },
    closeEditDialog() {

    },
    async changeUser(id) {
      const { data: res } = await this.$http.get('users/' + id)

      if(res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        return false
      }

      this.editRuleForm = res.data
      this.editDialogVisible = true
    },
    resetEditForm() {
      this.$refs.editRuleForm.resetFields()
      this.editDialogVisible = false
    },
    editUser(id) {
      this.$refs.editRuleForm.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put('users/' + id, {
            email: this.editRuleForm.email,
            mobile: this.editRuleForm.mobile
          })

          if(res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
            return false
          }

          this.editDialogVisible = false
          this.getUserList()
          this.$message.success(res.meta.msg)
        } else {
          this.$message.error('请填写完整表单信息')
          return false
        }
      })
    },
    delUser(id) {
      // 弹框
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('users/' + id)
        if(res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          return false
        }
        this.$message.success(res.meta.msg)
        this.getUserList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })      
      })
    },
    async distributeRoles(info) {
      this.rolesRuleForm = info
      this.rolesDialogVisible = true

      const { data: res } = await this.$http.get('roles')
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

      this.newRolesList = res.data

    },
    closeRolesDialog(){

    },
    async changeRole() {
      if(!this.selectRoleId) return this.$message.error('请选择角色')

      const { data: res } = await this.$http.put(`users/${this.rolesRuleForm.id}/role`, {rid: this.selectRoleId})
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

      this.$message.success(res.meta.msg)
      this.rolesDialogVisible = false
      this.getUserList()
      
    }
  }
}
</script>

<style lang="less">
  .users-container{
    .box-card{
      margin-top: 20px;
    }
    .el-table{
      margin: 20px 0;
    }
  }
</style>